import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Comment } from 'src/entities/comment.entity';
import { Repository } from 'typeorm';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
  ) {}

  async findAll(findOption={}): Promise<Comment[]> {
    const attentions=await this.commentRepository.find(findOption);
    return attentions;
  }

  async findOne(id: number): Promise<Comment> {
    return await this.commentRepository.findOne(id);
  }

  async removeOne(id: number): Promise<Comment> {
    const old=await this.findOne(id);
    const res=await this.commentRepository.delete(id);
    return res.affected===1?old:null;
  }

  async addOne(comment: Comment): Promise<Comment> {
    const u=Object.assign(new Comment(),comment);
    u.create_time=new Date();
    const res=await this.commentRepository.insert(u);
    return this.findOne(res.identifiers[0].id);
  }

  async modifyOne(id: number,comment: Comment): Promise<Comment> {
    const u=Object.assign(new Comment(),comment);
    const res=await this.commentRepository.update(id,u);
    return await this.findOne(id);
  }

  async count(option={}): Promise<number> {
    return await this.commentRepository.count(option);
  }

  async getPagination(page={},sort={},where={}){
    const p=Object.assign({
      size:10,
      current:0,
      total:0,
    },page);
    const ars=await this.findAll({
      order:sort,
      take:p.size,
      skip:p.current,
      where:where
    });
    const total = await this.count(where);
    p.total=total;
    return {
      page:p,
      comments:ars,
    }
  }
}
